﻿using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using DingTida.Models;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DingTida.IBLL;

namespace DingTida.BLL
{
    public class Token:IToken
    {


        public string access_token = "";
 
        public OapiUserGetuserinfoResponse rsp = null;
     
        public IMemoryCache Cache;

        public Token( IMemoryCache _cache )
        {
           
            this.Cache = _cache;

      
        }


        public  void SetToken()
        {

            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.Appkey = "ding5ibuqempqoqfzykn";//"dingt691drnrkopwdusb";
            req.Appsecret = "fctZRJClnx8eFiWgEbzUfKWyldx82sZTXxeAg5HKqubvb64oMMjwtj6fJgO2rIRj";//"zIH8e2rQrPxDglVHy21VZXoU-Y9CjQ581QjhRm2eA40gfIBQey2tyyg-sLEnz09e";
            req.SetHttpMethod("GET");
            OapiGettokenResponse rsp = client.Execute(req, access_token);
            Console.WriteLine(rsp.Body);
            // return Ok(new {token=rsp.AccessToken });
            access_token = rsp.AccessToken;


        }


        public string  GetToken()
        {
            var tokenstr = Cache.Get("token");
            if (tokenstr == null)
            {
                SetToken();
                Cache.Set("token", access_token, TimeSpan.FromSeconds(7100));
                return access_token;
            }
            else
            {


                return tokenstr.ToString();

            }



        }



    }
}
